<template>
	<view class="page" :class="{ 'night-mode': isNightMode }">
		<!-- 头部区域 -->
		<view class="header">
			<view class="user-info">
				<image class="avatar" src="/static/login.png" mode="aspectFill"></image>
				<view class="user-details">
					<text class="username">{{user.nickname}}</text>
					<text class="user-role">{{user.role==0 ? "学生" : "老师"}}</text>
				</view>
			</view>
			<view class="header-actions">
				<uni-icons type="search" size="24" color="#333"></uni-icons>
				<uni-icons type="chat" size="24" color="#333"></uni-icons>
				<view class="join-class-btn" @tap="showJoinClassModal">
					<uni-icons type="search" size="24" color="#fff"></uni-icons>
				</view>
			</view>
		</view>

		<!-- 主要内容 -->
		<view class="content">
			<!-- 快速访问区域 -->
			<view class="quick-access">
				<view class="quick-access-item" v-for="(item, index) in quickAccessList" :key="index" @tap="handleQuickAccess(item)">
					<text class="quick-access-text">{{ item }}</text>
				</view>
			</view>

			<!-- 消息动态区域 -->
			<view class="message-section">
				<view class="section-header">
					<view class="title-row">
						<text class="title-text" @tap="goToMessages">消息动态</text>
						<view class="tab-buttons">
							<text class="tab-button" :class="{ active: activeTab === 'message' }" @tap="switchTab('message')">消息</text>
							<text class="tab-button" :class="{ active: activeTab === 'unread' }" @tap="switchTab('unread')">未读</text>
						</view>
					</view>
				</view>
				<view class="message-list">
					<view class="message-item" v-for="(msg, index) in messageList" :key="index" @tap="handleMessageClick(msg)">
						<view class="avatar-circle">
							<text class="avatar-text">{{ msg.title.charAt(0) }}</text>
						</view>
						<view class="message-content">
							<view class="message-header">
								<view class="message-title-wrapper">
									<text class="message-title">{{ msg.title }}</text>
								</view>
								<text class="message-time">{{ msg.time }}</text>
							</view>
							<text class="message-preview">{{ msg.preview }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 课程安排区域 -->
			<view class="schedule-section">
				<view class="section-header">
					<text class="section-title">今日课程</text>
					<text class="section-more">查看全部</text>
				</view>
				<view class="schedule-list">
					<view class="schedule-item" v-for="(course, index) in scheduleList" :key="index">
						<view class="course-time">
							<text class="time-text">{{ course.time }}</text>
						</view>
						<view class="course-info">
							<text class="course-name">{{ course.name }}</text>
							<text class="course-teacher">{{ course.teacher }}</text>
						</view>
						<view class="course-status" :class="course.status">
							<text class="status-text">{{ course.statusText }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- AI悬浮助教 -->
		<ai-assistant></ai-assistant>
		
		<!-- 微信样式消息弹框 -->
		<view v-if="showMessagePopup && currentPopupMessage" class="message-popup" @tap="handlePopupClick">
			<view class="popup-content">
				<view class="popup-avatar">
					<text class="popup-avatar-text">{{ getPopupAvatarText() }}</text>
				</view>
				<view class="popup-message">
					<text class="popup-sender">{{ currentPopupMessage.title || '系统消息' }}</text>
					<text class="popup-content-text">{{ currentPopupMessage.preview || '' }}</text>
				</view>
				<text class="popup-time">{{ currentPopupMessage.time || '' }}</text>
			</view>
		</view>

		<!-- 加入班级模态框 -->
		<view v-if="showCreateModal" class="modal-overlay" @tap="closeCreateModal">
			<view class="modal-content" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">加入班级</text>
					<uni-icons type="close" size="20" color="#999" @tap="closeCreateModal"></uni-icons>
				</view>
				<view class="modal-body">
					<view class="form-item">
						<text class="form-label">班级ID</text>
						<input class="form-input" v-model="classForm.classId" placeholder="请输入班级ID" />
					</view>
					<view class="form-item">
						<text class="form-label">申请加入理由</text>
						<textarea class="form-textarea" v-model="classForm.reason" placeholder="请输入申请加入理由"></textarea>
					</view>
					<view class="form-item">
						<text class="form-label">邀请码（选填）</text>
						<input class="form-input" v-model="classForm.inviteCode" placeholder="请输入邀请码（可选）" />
					</view>
					<view class="form-actions">
						<button class="cancel-btn" @tap="closeCreateModal">取消</button>
						<button class="confirm-btn" @tap="joinClass">申请加入</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 日历模态框 -->
		<view v-if="showCalendarModal" class="modal-overlay" @tap="closeCalendarModal">
			<view class="modal-content calendar-modal" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">日历</text>
					<uni-icons type="close" size="20" color="#999" @tap="closeCalendarModal"></uni-icons>
				</view>
				<view class="modal-body">
					<view class="calendar-header">
						<text class="calendar-title">{{ currentDate.getFullYear() }}年{{ currentDate.getMonth() + 1 }}月</text>
					</view>
					<view class="calendar-grid">
						<view class="calendar-day" v-for="day in 31" :key="day" 
							:class="{ 'selected': selectedDate.getDate() === day }"
							@tap="selectDate(day)">
							<text class="day-number">{{ day }}</text>
						</view>
					</view>
					<view class="calendar-events">
						<text class="events-title">今日安排</text>
						<view class="event-item" v-for="todo in todayTodos" :key="todo.id">
							<text class="event-text">{{ todo.title }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 待办模态框 -->
		<view v-if="showTodoModal" class="modal-overlay" @tap="closeTodoModal">
			<view class="modal-content todo-modal" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">待办事项</text>
					<uni-icons type="close" size="20" color="#999" @tap="closeTodoModal"></uni-icons>
				</view>
				<view class="modal-body">
					<view class="todo-list">
						<view class="todo-item" v-for="todo in todoList" :key="todo.id"
							:class="{ 'completed': todo.completed }">
							<view class="todo-checkbox" @tap="toggleTodo(todo.id)">
								<uni-icons v-if="todo.completed" type="checkmarkempty" size="20" color="#4CAF50"></uni-icons>
							</view>
							<text class="todo-title">{{ todo.title }}</text>
							<text class="todo-date">{{ todo.date }}</text>
						</view>
					</view>
					<view class="add-todo-section">
						<input class="add-todo-input" v-model="newTodoTitle" placeholder="添加新待办" />
						<button class="add-todo-btn" @tap="addTodo">添加</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted, onUnmounted } from 'vue';
	import AiAssistant from '@/components/ai-assistant/ai-assistant.vue';
	import themeManager from '@/utils/theme.js';
	import { API_BASE_URL } from '../../static/constants'
	

	// 夜间模式状态
	const isNightMode = ref(themeManager.getNightMode());

	// 主题变化回调
	const onThemeChanged = (newMode: boolean) => {
		isNightMode.value = newMode;
	};

	// 快速访问列表
	const quickAccessList = ref(['我的班级', '日历', '待办']);

	// 当前激活的标签
	const activeTab = ref('message');

	// 计算消息列表（从班级列表生成）
	const messageList = ref([]);
	const user = ref({
		nickname:'',
		role: 1,
	});
	
	// 消息弹框相关
	const showMessagePopup = ref(false);
	const currentPopupMessage = ref({});
	let popupTimer: NodeJS.Timeout | null = null;
	// 课程安排数据
	const scheduleList = ref([
		{
			time: '08:00',
			name: '高等数学',
			teacher: '张教授',
			status: 'upcoming',
			statusText: '即将开始'
		},
		{
			time: '10:00',
			name: '英语口语',
			teacher: '外教Mike',
			status: 'live',
			statusText: '直播中'
		},
		{
			time: '14:00',
			name: '物理实验',
			teacher: '李老师',
			status: 'completed',
			statusText: '已完成'
		}
	]);

	// 加入班级相关数据
	const showCreateModal = ref(false);
	const classForm = ref({
		classId: '',
		reason: '',
		inviteCode: ''
	});

	// 班级列表数据
	const classList = ref([
		
	]);

	// 日历和待办相关数据
	const showCalendarModal = ref(false);
	const showTodoModal = ref(false);
	const currentDate = ref(new Date());
	const selectedDate = ref(new Date());
	const todoList = ref([
		{ id: 1, title: '提交高等数学作业', date: '2024-01-15', completed: false },
		{ id: 2, title: '准备英语口语课', date: '2024-01-16', completed: false },
		{ id: 3, title: '查看物理实验成绩', date: '2024-01-15', completed: true }
	]);

	// 处理快速访问点击
	const handleQuickAccess = (item: string) => {
		switch (item) {
			case '我的班级':
				uni.navigateTo({
					url: '/pages/my-classes/my-classes'
				});
				break;
			case '日历':
				openCalendarModal();
				break;
			case '待办':
				openTodoModal();
				break;
			default:
				uni.showToast({
					title: `点击了${item}`,
					icon: 'none'
				});
		}
	};

	// 跳转到消息页面
	const goToMessages = () => {
		uni.navigateTo({
			url: '/pages/messages/messages'
		});
	};

	// 切换消息标签
	const switchTab = (tab: string) => {
		activeTab.value = tab;
		uni.showToast({
			title: `切换到${tab === 'message' ? '消息' : '未读'}`,
			icon: 'none'
		});
	};

	// 处理消息点击
	const handleMessageClick = (msg: any) => {
		console.log('📱 点击消息:', msg);
		
		// 保存消息到本地存储，供详情页使用
		const savedMessages = uni.getStorageSync('messageList') || [];
		const existingIndex = savedMessages.findIndex((m: any) => m.id === msg.id);
		
		if (existingIndex === -1) {
			savedMessages.push(msg);
			uni.setStorageSync('messageList', savedMessages);
		}
		
		// 跳转到消息详情页面
		uni.navigateTo({
			url: `/pages/message-detail/message-detail?messageId=${msg.id}&messageData=${encodeURIComponent(JSON.stringify(msg))}`
		});
	};
	
	// 格式化消息时间显示
	const formatMessageTime = (timeString) => {
		if (!timeString) return '';
		const date = new Date(timeString);
		const now = new Date();
		
		// 如果是今天的消息，只显示时间
		if (date.toDateString() === now.toDateString()) {
			return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
		}
		
		// 如果是昨天或更早，显示日期
		return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
	};
	// 显示加入班级模态框
	const showJoinClassModal = () => {
		showCreateModal.value = true;
	};

	// 显示日历模态框
	const openCalendarModal = () => {
		showCalendarModal.value = true;
	};

	// 显示待办模态框
	const openTodoModal = () => {
		showTodoModal.value = true;
	};

	// 关闭日历模态框
	const closeCalendarModal = () => {
		showCalendarModal.value = false;
	};

	// 关闭待办模态框
	const closeTodoModal = () => {
		showTodoModal.value = false;
	};

	// 选择日期
	const selectDate = (day: number) => {
		selectedDate.value = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth(), day);
	};

	// 切换待办状态
	const toggleTodo = (id: number) => {
		const todo = todoList.value.find(t => t.id === id);
		if (todo) {
			todo.completed = !todo.completed;
		}
	};

	// 添加新待办
	const newTodoTitle = ref('');
	const addTodo = () => {
		if (newTodoTitle.value.trim()) {
			const newTodo = {
				id: Date.now(),
				title: newTodoTitle.value,
				date: new Date().toISOString().split('T')[0],
				completed: false
			};
			todoList.value.push(newTodo);
			newTodoTitle.value = '';
		}
	};

	// 计算今日待办
	const todayTodos = computed(() => {
		const today = new Date().toISOString().split('T')[0];
		return todoList.value.filter(todo => todo.date === today);
	});

	// 关闭加入班级模态框
	const closeCreateModal = () => {
		showCreateModal.value = false;
		// 重置表单
		classForm.value = {
			classId: '',
			reason: '',
			inviteCode: ''
		};
	};



	// 加入班级
	const joinClass = () => {
		// 表单验证
		if (!classForm.value.classId.trim()) {
			uni.showToast({
				title: '请输入班级ID',
				icon: 'none'
			});
			return;
		}

		if (!classForm.value.reason.trim()) {
			uni.showToast({
				title: '请输入申请加入理由',
				icon: 'none'
			});
			return;
		}

		// BACKEND REQUIRED: 加入班级API
		// POST /api/class/join
		// Request Body:
		// {
		//   classId: string,
		//   reason: string,
		//   inviteCode: string (可选)
		// }
		
		uni.showLoading({
			title: '申请中...'
		});

		// 模拟API调用
		setTimeout(() => {
			uni.hideLoading();
			
			// 模拟成功响应
			uni.showToast({
				title: '申请已提交',
				icon: 'success'
			});

			// 模拟班级信息（实际应该从后端获取）
			const targetClass = {
				id: classForm.value.classId,
				name: `班级${classForm.value.classId}`,
				description: '待审核的班级',
				avatar: '',
				lastMessage: '申请已提交，等待审核',
				time: '刚刚',
				unreadCount: 0
			};

			// 关闭模态框
			closeCreateModal();

			// BACKEND REQUIRED: 刷新用户班级列表
			// GET /api/user/classes
		}, 1500);
	};
	// 智能初始化用户信息
	const initializeUserInfo = () => {
		console.log('🚀 开始初始化用户信息');
		
		const tokenData = uni.getStorageSync('token');
		console.log('🔑 获取到的token数据:', tokenData);
		
		if (!tokenData) {
			console.error('❌ 没有token，跳转到登录页');
			uni.showToast({ title: '请先登录', icon: 'none' });
			setTimeout(() => {
				uni.reLaunch({ url: '/pages/login/login' });
			}, 1500);
			return;
		}
		
		// 智能处理token格式
		if (typeof tokenData === 'object' && tokenData.token) {
			console.log('📦 检测到token对象格式，直接提取用户信息');
			
			// 直接从token对象获取用户信息
			user.value = {
				nickname: tokenData.nickname || '未设置昵称',
				username: tokenData.username || '未知账号',
				role: tokenData.role || 0,
				id: tokenData.userId,
				avatar: tokenData.avatar || null,
				phone: tokenData.phone || '',
				age: tokenData.age || null,
				gender: tokenData.gender || null
			};
			
			console.log('✅ 用户信息已从token加载:', user.value);
			
			// 保存userId到独立存储
			if (tokenData.userId) {
				uni.setStorageSync('userId', tokenData.userId);
			}
			
			// 使用真实用户ID获取消息
			setTimeout(() => {
				loadMessagesWithRetry(tokenData.userId || '2025048');
			}, 1000);
			
			// 验证token有效性（后台验证）
			if (tokenData.token) {
				validateTokenInBackground(tokenData.token);
			}
			
		} else {
			console.log('📝 检测到字符串token格式，尝试从userInfo获取用户信息');
			
			// 尝试从userInfo获取用户信息，避免token验证失败导致闪退
			const userInfoData = uni.getStorageSync('userInfo');
			if (userInfoData && userInfoData.id) {
				console.log('✅ 从userInfo获取用户信息成功');
				user.value = {
					nickname: userInfoData.nickname || userInfoData.name || '未设置昵称',
					username: userInfoData.username || '未知账号',
					role: userInfoData.role || 1,
					id: userInfoData.id,
					avatar: userInfoData.avatar || null,
					phone: userInfoData.phone || '',
					age: userInfoData.age || null,
					gender: userInfoData.gender || null
				};
				
				// 保存userId到独立存储
				uni.setStorageSync('userId', userInfoData.id);
				
				// 使用用户ID获取消息
				setTimeout(() => {
					loadMessagesWithRetry(userInfoData.id || '2025048');
				}, 1000);
				
				// 可选的后台验证（不影响用户体验）
				if (typeof tokenData === 'string') {
					validateTokenInBackground(tokenData);
				}
			} else {
				console.warn('⚠️ 未找到userInfo，进行token验证');
				validateToken(tokenData);
			}
		}
	};
	
	// 后台验证token有效性
	const validateTokenInBackground = (tokenString: string) => {
		console.log('🔍 后台验证token有效性');
		
		uni.request({
			url: API_BASE_URL + '9001/user/validate',
			method: 'GET',
			header: {
				'Authorization': 'Bearer ' + tokenString
			},
			success: (res) => {
				const responseData = res.data as {
					code: number;
					message: string;
					data: any;
				};
				
				if (responseData.code === 200) {
					console.log('✅ Token验证通过');
				} else {
					console.warn('⚠️ Token可能已过期');
				}
			},
			fail: (err) => {
				console.warn('⚠️ Token验证失败:', err);
			}
		});
	};

	// 验证token并获取用户信息
	const validateToken = (tokenData: any) => {
		console.log('🔍 验证token并获取用户信息');
		
		let tokenString = '';
		
		// 提取真实的token字符串
		if (typeof tokenData === 'string') {
			tokenString = tokenData;
		} else if (typeof tokenData === 'object' && tokenData.token) {
			tokenString = tokenData.token;
		}
		
		if (!tokenString) {
			console.error('❌ 无法提取有效的token字符串');
			return;
		}
		
		uni.request({
			url: API_BASE_URL + '9001/user/validate',
			method: 'GET',
			header: {
				'Authorization': 'Bearer ' + tokenString
			},
			success: (res) => {
				const responseData = res.data as {
					code: number;
					message: string;
					data: any;
				};
				
				if (responseData.code === 200 && responseData.data) {
					console.log('✅ Token验证成功，获取用户详情');
					uni.setStorageSync('userId', responseData.data);
					findUser(responseData.data);
				} else {
					console.warn('⚠️ Token验证失败，使用默认用户信息:', responseData.message);
					// 不强制跳转，设置默认用户信息让用户继续使用
					user.value = {
						nickname: '用户',
						username: '未验证用户',
						role: 1,
						id: '2025048', // 使用默认ID
						avatar: null,
						phone: '',
						age: null,
						gender: null
					};
					// 提示用户但不强制退出
					uni.showToast({ title: '身份验证失败，使用访客模式', icon: 'none' });
				}
			},
			fail: (err) => {
				console.warn('⚠️ Token验证请求失败，使用默认用户信息:', err);
				// 网络失败时也不强制退出，设置默认用户信息
				user.value = {
					nickname: '访客用户',
					username: '网络未连接',
					role: 1,
					id: '2025048', // 使用默认ID
					avatar: null,
					phone: '',
					age: null,
					gender: null
				};
				uni.showToast({ title: '网络连接失败，使用离线模式', icon: 'none' });
			}
		});
	};

	// 获取用户详细信息
	const findUser = (userId: string) => {
		console.log('👤 获取用户详细信息, UserId:', userId);
		
		uni.request({
			url: API_BASE_URL + '9001/user/find-by-id',
			method: 'GET',
			data: {
				id: userId
			},
			success: (res) => {
				const responseData = res.data as {
					code: number;
					message: string;
					data: any;
				};
				
				if (responseData.code === 200 && responseData.data) {
					console.log('✅ 用户信息获取成功:', responseData.data);
					user.value = {
						...responseData.data,
						nickname: responseData.data.nickname || '未设置昵称',
						username: responseData.data.username || '未知账号'
					};
					
					// 保存用户信息到本地
					uni.setStorageSync('userInfo', user.value);
					
					// 显示欢迎消息
					uni.showToast({
						title: `欢迎 ${user.value.nickname}`,
						icon: 'success',
						duration: 1500
					});
					
					// 获取消息列表
					setTimeout(() => {
						loadMessagesWithRetry(userId);
					}, 1000);
					
				} else {
					console.error('❌ 获取用户信息失败:', responseData.message);
					user.value = {
						nickname: '获取失败',
						username: '获取失败',
						role: 0,
						id: null,
						avatar: null,
						phone: '',
						age: null,
						gender: null
					};
				}
			},
			fail: (err) => {
				console.error('❌ 获取用户信息请求失败:', err);
				user.value = {
					nickname: '网络错误',
					username: '网络错误',
					role: 0,
					id: null,
					avatar: null,
					phone: '',
					age: null,
					gender: null
				};
			}
		});
	};

	// 带重试机制的消息加载
	const loadMessagesWithRetry = (userId: string) => {
		console.log('📨 开始加载消息，用户ID:', userId);
		
		const messageUrls = [
			API_BASE_URL + '9003/message/getMessage',
			'http://localhost:9003/message/getMessage',
			'http://127.0.0.1:9003/message/getMessage'
		];
		
		let currentUrlIndex = 0;
		
		const tryRequest = () => {
			if (currentUrlIndex >= messageUrls.length) {
				console.log('🚫 所有消息服务地址都无法连接，显示演示消息');
				showDemoMessages();
				return;
			}
			
			const currentUrl = messageUrls[currentUrlIndex];
			console.log(`🌐 尝试连接消息服务 (${currentUrlIndex + 1}/${messageUrls.length}):`, currentUrl);
			
			uni.request({
				url: currentUrl,
				data: {
					toUser: userId
				},
				header: {
					'custom-header': 'application/json'
				},
				timeout: 5000,
				success: (res) => {
					console.log('📬 消息获取成功:', res.data);
					if (res.data && Array.isArray(res.data) && res.data.length > 0) {
						const messages = res.data.slice(0, 3);
						messageList.value = messages.map(msg => ({
							id: msg.messageid,
							title: `用户${msg.fromUser}`,
							time: formatMessageTime(msg.sendTime),
							preview: msg.content,
							isRead: msg.isRead || false
						}));
						
						const unreadCount = res.data.filter(msg => !msg.isRead).length;
						if (unreadCount > 0) {
							uni.showToast({
								title: `您有 ${unreadCount} 条新消息`,
								icon: 'none',
								duration: 2000
							});
						}
						
						console.log('✅ 真实消息加载完成');
					} else {
						console.log('📭 暂无新消息，显示演示消息');
						showDemoMessages();
					}
				},
				fail: (err) => {
					console.log(`❌ 消息服务连接失败 (${currentUrlIndex + 1}/${messageUrls.length}):`, err.errMsg);
					currentUrlIndex++;
					tryRequest();
				}
			});
		};
		
		tryRequest();
	};

	// 显示演示消息
	const showDemoMessages = () => {
		console.log('🎭 显示演示消息');
		
		// 直接显示演示消息，避免再次尝试连接失败的服务
		const demoMessages = [
			{
				id: "demo_system",
				title: "系统通知",
				time: "刚刚",
				preview: "欢迎使用EduLiveLink教育平台！",
				isRead: false
			},
			{
				id: "demo_teacher",
				title: "张教授",
				time: "10分钟前",
				preview: "请注意：明天上午9点有重要的数学测验，请准时参加",
				isRead: false
			},
			{
				id: "demo_assignment",
				title: "作业通知",
				time: "1小时前",
				preview: "新作业已发布：数据结构与算法练习，截止时间本周五",
				isRead: true
			}
		];
		
		messageList.value = demoMessages;
		
		// 显示微信样式弹框通知
		if (demoMessages.length > 0) {
			setTimeout(() => {
				showWeChatStylePopup(demoMessages[0]);
			}, 1000);
			
			// 如果有多条消息，依次显示
			if (demoMessages.length > 1) {
				setTimeout(() => {
					showWeChatStylePopup(demoMessages[1]);
				}, 4000);
			}
		}
		
		console.log('🎭 演示消息已加载:', demoMessages.length, '条');
	};
	
	// 显示微信样式弹框
	const showWeChatStylePopup = (message: any) => {
		console.log('💬 显示微信样式弹框:', message);
		
		// 清除之前的定时器
		if (popupTimer) {
			clearTimeout(popupTimer);
		}
		
		currentPopupMessage.value = message;
		showMessagePopup.value = true;
		
		// 3秒后自动隐藏
		popupTimer = setTimeout(() => {
			hideMessagePopup();
		}, 3000);
	};
	
	// 隐藏消息弹框
	const hideMessagePopup = () => {
		showMessagePopup.value = false;
		currentPopupMessage.value = {};
		if (popupTimer) {
			clearTimeout(popupTimer);
			popupTimer = null;
		}
	};
	
	// 点击弹框
	const handlePopupClick = () => {
		console.log('📱 点击弹框:', currentPopupMessage.value);
		hideMessagePopup();
		
		// 直接跳转到消息详情页面
		if (currentPopupMessage.value && currentPopupMessage.value.id) {
			// 保存消息到本地存储
			const savedMessages = uni.getStorageSync('messageList') || [];
			const existingIndex = savedMessages.findIndex((m: any) => m.id === currentPopupMessage.value.id);
			
			if (existingIndex === -1) {
				savedMessages.push(currentPopupMessage.value);
				uni.setStorageSync('messageList', savedMessages);
			}
			
			// 跳转到消息详情页面
			uni.navigateTo({
				url: `/pages/message-detail/message-detail?messageId=${currentPopupMessage.value.id}&messageData=${encodeURIComponent(JSON.stringify(currentPopupMessage.value))}`
			});
		}
	};
	
	// 获取弹框头像文字
	const getPopupAvatarText = () => {
		if (!currentPopupMessage.value || !currentPopupMessage.value.title) return '消';
		return currentPopupMessage.value.title.charAt(0);
	};

	// 生命周期钩子
	onMounted(() => {
		console.log('📱 Home页面加载开始');
		
		// 添加主题变化监听器
		themeManager.addListener(onThemeChanged);
		
		// 智能初始化用户信息和消息
		initializeUserInfo();
	});

	onUnmounted(() => {
		// 移除主题变化监听器
		themeManager.removeListener(onThemeChanged);
	});
</script>

<style>
	page {
		background-color: #f5f5f5;
		transition: background-color 0.3s ease;
	}

	.page {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		transition: all 0.3s ease;
	}

	/* 夜间模式样式 */
	.night-mode {
		background-color: #1a1a1a;
	}

	.night-mode .header {
		background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
	}

	.night-mode .message-section,
	.night-mode .schedule-section {
		background: #2c2c2c;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
	}

	.night-mode .section-title,
	.night-mode .message-title,
	.night-mode .course-name {
		color: #e0e0e0;
	}

	.night-mode .message-preview,
	.night-mode .course-teacher {
		color: #b0b0b0;
	}

	.night-mode .message-item {
		border-bottom-color: #3a3a3a;
	}

	.night-mode .schedule-item {
		border-bottom-color: #3a3a3a;
	}

	.header {
		width: 100%;
		background: linear-gradient(135deg, #1976D2 0%, #64B5F6 100%);
		padding: 40rpx 30rpx 30rpx;
		padding-top: calc(40rpx + env(safe-area-inset-top));
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.user-info {
		display: flex;
		align-items: center;
	}

	.avatar {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		margin-right: 20rpx;
		border: 3rpx solid rgba(255, 255, 255, 0.3);
	}

	.user-details {
		display: flex;
		flex-direction: column;
	}

	.username {
		font-size: 32rpx;
		color: #ffffff;
		font-weight: 600;
		margin-bottom: 8rpx;
	}

	.user-role {
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.8);
	}

	.header-actions {
		display: flex;
		gap: 30rpx;
	}

	.content {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 30rpx;
		flex: 1;
	}

	.quick-access {
		width: 100%;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 30rpx;
		margin-bottom: 40rpx;
	}

	.quick-access-item {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 60rpx 20rpx;
		text-align: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
		border: 2rpx solid #f0f0f0;
	}

	.quick-access-item:active {
		transform: scale(0.95);
	}

	.quick-access-text {
		font-size: 32rpx;
		color: #333333;
		font-weight: 600;
	}

	.message-section {
		width: 100%;
		background: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.section-header {
		margin-bottom: 30rpx;
	}

	.title-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		gap: 20rpx;
	}

	.title-text {
		font-size: 32rpx;
		color: #333333;
		font-weight: 600;
	}

	.tab-buttons {
		display: flex;
		gap: 20rpx;
	}

	.tab-button {
		font-size: 26rpx;
		color: #999999;
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		transition: all 0.3s ease;
	}

	.tab-button.active {
		color: #1976D2;
		background: rgba(25, 118, 210, 0.1);
	}

	.message-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.message-item {
		display: flex;
		align-items: flex-start;
		gap: 20rpx;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
		width: 100%;
		transition: all 0.3s ease;
	}

	.message-item:active {
		background-color: #f5f5f5;
		transform: scale(0.98);
	}

	.message-item:last-child {
		border-bottom: none;
	}

	.avatar-circle {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background: #1976D2;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.avatar-text {
		color: #ffffff;
		font-size: 28rpx;
		font-weight: 600;
	}

	.message-content {
		flex: 1;
		min-width: 0;
		width: calc(100% - 100rpx);
		padding-right: 20rpx;
	}

	.message-header {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		margin-bottom: 8rpx;
		gap: 50rpx;
	}

	.message-title-wrapper {
		flex: 1;
		min-width: 0;
		max-width: calc(100% - 160rpx);
	}

	.message-title {
		font-size: 28rpx;
		color: #333333;
		font-weight: 500;
		display: block;
		margin-bottom: 4rpx;
		word-break: break-all;
	}

	.message-time {
		font-size: 24rpx;
		color: #999999;
		flex-shrink: 0;
		white-space: nowrap;
		min-width: 100rpx;
		text-align: right;
		padding-right: 10rpx;
	}

	.message-preview {
		font-size: 12px;
		color: #666;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 1;
		overflow: hidden;
		max-width: calc(100% - 160rpx);
		word-break: break-all;
	}

	.schedule-section {
		width: 100%;
		background: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	}

	.section-title {
		font-size: 32rpx;
		color: #333333;
		font-weight: 600;
		margin-bottom: 20rpx;
		display: block;
	}

	.section-more {
		font-size: 26rpx;
		color: #1976D2;
	}

	.schedule-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.schedule-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
	}

	.course-time {
		width: 120rpx;
		text-align: center;
		margin-right: 20rpx;
	}

	.time-text {
		font-size: 24rpx;
		color: #666666;
	}

	.course-info {
		flex: 1;
	}

	.course-name {
		font-size: 28rpx;
		color: #333333;
		font-weight: 500;
		display: block;
		margin-bottom: 8rpx;
	}

	.course-teacher {
		font-size: 24rpx;
		color: #999999;
		display: block;
	}

	.course-status {
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
		margin-left: 20rpx;
	}

	.course-status.upcoming {
		background: rgba(255, 152, 0, 0.1);
	}

	.course-status.live {
		background: rgba(244, 67, 54, 0.1);
	}

	.course-status.completed {
		background: rgba(76, 175, 80, 0.1);
	}

	.status-text {
		font-size: 22rpx;
		color: #666666;
	}

	.course-status.upcoming .status-text {
		color: #FF9800;
	}

	.course-status.live .status-text {
		color: #F44336;
	}

	.course-status.completed .status-text {
		color: #4CAF50;
	}

	/* 加入班级按钮 */
	.join-class-btn {
		width: 60rpx;
		height: 60rpx;
		background: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		backdrop-filter: blur(10rpx);
		border: 2rpx solid rgba(255, 255, 255, 0.3);
		transition: all 0.3s ease;
	}

	.join-class-btn:active {
		transform: scale(0.9);
		background: rgba(255, 255, 255, 0.3);
	}



	/* 加入班级模态框样式 */
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.modal-content {
		background: #fff;
		border-radius: 20rpx;
		width: 90%;
		max-width: 600rpx;
		max-height: 80vh;
		overflow: hidden;
	}

	.modal-header {
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.modal-body {
		padding: 30rpx;
		max-height: 60vh;
		overflow-y: auto;
	}

	.form-item {
		margin-bottom: 30rpx;
	}

	.form-label {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 15rpx;
		display: block;
	}

	.form-input {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #ddd;
		border-radius: 12rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		background: #f8f9fa;
	}

	.form-textarea {
		width: 100%;
		height: 120rpx;
		border: 1rpx solid #ddd;
		border-radius: 12rpx;
		padding: 20rpx;
		font-size: 28rpx;
		background: #f8f9fa;
		resize: none;
	}

	.picker-input {
		width: 100%;
		height: 80rpx;
		border: 1rpx solid #ddd;
		border-radius: 12rpx;
		padding: 0 20rpx;
		font-size: 28rpx;
		background: #f8f9fa;
		display: flex;
		align-items: center;
		color: #333;
	}



	.form-actions {
		display: flex;
		gap: 20rpx;
		margin-top: 40rpx;
	}

	.cancel-btn, .confirm-btn {
		flex: 1;
		height: 80rpx;
		border-radius: 12rpx;
		font-size: 28rpx;
		border: none;
	}

	.cancel-btn {
		background: #f5f5f5;
		color: #666;
	}

	.confirm-btn {
		background: #1976D2;
		color: #fff;
	}

	/* 夜间模式样式 */
	.night-mode .modal-content {
		background: #2c2c2c;
	}

	.night-mode .modal-title {
		color: #e0e0e0;
	}

	.night-mode .form-label {
		color: #e0e0e0;
	}

	.night-mode .form-input,
	.night-mode .form-textarea,
	.night-mode .picker-input {
		background: #3a3a3a;
		border-color: #4a4a4a;
		color: #e0e0e0;
	}



	.night-mode .cancel-btn {
		background: #3a3a3a;
		color: #e0e0e0;
	}

	/* 日历模态框样式 */
	.calendar-modal {
		max-width: 700rpx;
	}

	.calendar-header {
		text-align: center;
		margin-bottom: 30rpx;
	}

	.calendar-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.calendar-grid {
		display: grid;
		grid-template-columns: repeat(7, 1fr);
		gap: 10rpx;
		margin-bottom: 30rpx;
	}

	.calendar-day {
		aspect-ratio: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 8rpx;
		background: #f8f9fa;
		transition: all 0.3s ease;
	}

	.calendar-day.selected {
		background: #1976D2;
	}

	.calendar-day.selected .day-number {
		color: #fff;
	}

	.day-number {
		font-size: 24rpx;
		color: #333;
	}

	.calendar-events {
		border-top: 1rpx solid #f0f0f0;
		padding-top: 20rpx;
	}

	.events-title {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 15rpx;
		display: block;
	}

	.event-item {
		padding: 10rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.event-text {
		font-size: 26rpx;
		color: #666;
	}

	/* 待办模态框样式 */
	.todo-modal {
		max-width: 600rpx;
	}

	.todo-list {
		margin-bottom: 30rpx;
	}

	.todo-item {
		display: flex;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.todo-item.completed .todo-title {
		text-decoration: line-through;
		color: #999;
	}

	.todo-checkbox {
		width: 40rpx;
		height: 40rpx;
		border: 2rpx solid #ddd;
		border-radius: 6rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		background: #fff;
	}

	.todo-title {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.todo-date {
		font-size: 24rpx;
		color: #999;
		margin-left: 20rpx;
	}

	.add-todo-section {
		display: flex;
		gap: 15rpx;
		align-items: center;
	}

	.add-todo-input {
		flex: 1;
		height: 60rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
		padding: 0 15rpx;
		font-size: 26rpx;
		background: #f8f9fa;
	}

	.add-todo-btn {
		height: 60rpx;
		padding: 0 30rpx;
		background: #1976D2;
		color: #fff;
		border: none;
		border-radius: 8rpx;
		font-size: 26rpx;
	}

	/* 夜间模式样式 */
	.night-mode .calendar-title {
		color: #e0e0e0;
	}

	.night-mode .calendar-day {
		background: #3a3a3a;
	}

	.night-mode .day-number {
		color: #e0e0e0;
	}

	.night-mode .events-title {
		color: #e0e0e0;
	}

	.night-mode .event-text {
		color: #b0b0b0;
	}

	.night-mode .todo-title {
		color: #e0e0e0;
	}

	.night-mode .todo-checkbox {
		background: #3a3a3a;
		border-color: #4a4a4a;
	}

	.night-mode .add-todo-input {
		background: #3a3a3a;
		border-color: #4a4a4a;
		color: #e0e0e0;
	}
	
	/* 微信样式消息弹框 */
	.message-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 9999;
		padding-top: var(--status-bar-height);
		padding-top: calc(var(--status-bar-height) + 10rpx);
		animation: slideDown 0.3s ease-out;
	}
	
	.popup-content {
		background: rgba(0, 0, 0, 0.85);
		margin: 20rpx;
		border-radius: 16rpx;
		padding: 24rpx;
		display: flex;
		align-items: center;
		backdrop-filter: blur(10rpx);
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
	}
	
	.popup-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		flex-shrink: 0;
	}
	
	.popup-avatar-text {
		color: white;
		font-size: 24rpx;
		font-weight: bold;
	}
	
	.popup-message {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
		min-width: 0;
	}
	
	.popup-sender {
		color: white;
		font-size: 28rpx;
		font-weight: 600;
		line-height: 1.2;
	}
	
	.popup-content-text {
		color: rgba(255, 255, 255, 0.8);
		font-size: 24rpx;
		line-height: 1.3;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.popup-time {
		color: rgba(255, 255, 255, 0.6);
		font-size: 20rpx;
		margin-left: 16rpx;
		flex-shrink: 0;
	}
	
	/* 动画效果 */
	@keyframes slideDown {
		0% {
			transform: translateY(-100%);
			opacity: 0;
		}
		100% {
			transform: translateY(0);
			opacity: 1;
		}
	}
	
	/* 夜间模式适配 */
	.night-mode .popup-content {
		background: rgba(44, 44, 46, 0.95);
	}
</style>
